package org.easy.eao.spring.schema;

import org.easy.eao.spring.DefaultActionSet;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.ManagedSet;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DefaultActionsDefinitionParser implements BeanDefinitionParser {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		GenericBeanDefinition def = new GenericBeanDefinition();
		// 设置Bean Class
		def.setBeanClass(DefaultActionSet.class);
		// 默认 Action 集合
		ManagedSet set = new ManagedSet();
		NodeList nodeList = element.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element e = (Element) node;
				if (e.getLocalName().equals(EaoSchemaNames.ACTION_ELEMENT)) {
					String action = e.getAttribute(EaoSchemaNames.ACTION_ATTRIBUTE_CLASS);
					set.add(new TypedStringValue(action, Class.class));
				}
			}
		}
		if (set.size() > 0) {
			MutablePropertyValues prop = new MutablePropertyValues();
			prop.addPropertyValue(DefaultActionSet.ATTRIBUTE_CLASSES, set);
			def.setPropertyValues(prop);
			return def;
		} else {
			return null;
		}
	}
	
}
